package com.mobily.teamaster.reports.client.screen;

import java.util.LinkedHashMap;

import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.TitleOrientation;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.Label;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.ComboBoxItem;
import com.smartgwt.client.widgets.form.fields.DateItem;
import com.smartgwt.client.widgets.form.fields.RadioGroupItem;
import com.smartgwt.client.widgets.layout.VLayout;

public class ReportScreen extends Composite {
	static final int REPORT_ON_POINTS = 1;
	static final int REPORT_ON_COUNT = 2;
	static final int REPORT_ON_RATING = 3;
	
	VLayout layout;
	VerticalPanel mainPanel;

	public ReportScreen() {
		init();
	}

	public void init(){
		mainPanel = new VerticalPanel();
//		criteriaVPanel.add()
		 layout = new VLayout(8); 
		 layout.setLeft(15);
		 
		 initWidget(layout);
		 
		 DynamicForm form = new DynamicForm();  
	        form.setMaxWidth(400);  
//	        form.setHeight(22);  
	        form.setTitleOrientation(TitleOrientation.TOP);  
	        
//	        TextItem empty = new TextItem("");
//	        empty.sete
//	        empty.setVisible(false);
	        
	        final RadioGroupItem reportType = new RadioGroupItem();
	        reportType.setTitle("Report On");
	        reportType.setValueMap("Points", "Activity Count");
	        reportType.setValue("Points");
	        reportType.setWidth(200);
	        reportType.setEndRow(true);
	        
//	        reportType.addBlurHandler(handler)
//	        final DateRangeItem createdRangeItem = new DateRangeItem("Activity");  
//	        createdRangeItem.setWidth("*");  
//	        createdRangeItem.setShowTitle(true);  
//	        createdRangeItem.setAllowRelativeDates(true);  
	        
	        final DateItem reportFromDate = new DateItem ("From");
	        final DateItem reportToDate = new DateItem ("To");
	        
//	        DateRange dateRange = new DateRange();  
//	        dateRange.setRelativeStartDate(new RelativeDate("-1200m"));  
//	        dateRange.setRelativeEndDate(new RelativeDate("-1000m"));  
//	        createdRangeItem.setValue(dateRange);  
	  
//	        form.setItems(createdRangeItem);
	        
	        final ComboBoxItem activityCombo = new ComboBoxItem();  
	        activityCombo.setTitle("Activity");  
//	        activityCombo.setHint("<nobr>Select Activity</nobr>");  
	        activityCombo.setType("comboBox");  
	        activityCombo.setValueMap("All", "onTime", "clean", "smile", "lookgood", "like", "Espresso", "Capuchino", "Tea", "Choclate"); 
	        activityCombo.setValue("All");
	        
	        final ComboBoxItem userTypeCombo = new ComboBoxItem();  
	        userTypeCombo.setTitle("User Type");  
//	        userTypeCombo.setHint("<nobr>Select User Type</nobr>");  
	        userTypeCombo.setType("comboBox");  
	        userTypeCombo.setValueMap("All", "STF", "VND", "MGR"); 
	        userTypeCombo.setValue("All");
	        
//	        final SelectItem groupBySelect = new SelectItem();  
//	        groupBySelect.setTitle("Group By");  
//	        groupBySelect.setMultiple(false);  
//	        groupBySelect.setMultipleAppearance(MultipleAppearance.GRID);  
//	        LinkedHashMap<String, String> groupByColumnMap = new LinkedHashMap<String, String>();
//	        groupByColumnMap.clear();
//	        groupByColumnMap.put("col3", "Date");
//	        groupByColumnMap.put("col2", "Tea Boy");
//	        groupByColumnMap.put("col0", "Activity");
//	        groupBySelect.setValueMap(groupByColumnMap);  
	  
	        final ComboBoxItem groupBySelect = new ComboBoxItem();  
	        groupBySelect.setTitle("Group By");  
	        LinkedHashMap<String, String> groupByColumnMap = new LinkedHashMap<String, String>();
	        groupByColumnMap.clear();
	        groupByColumnMap.put("col3", "Date");
	        groupByColumnMap.put("col2", "Tea Boy");
	        groupByColumnMap.put("col0", "Activity");
	        groupBySelect.setValueMap(groupByColumnMap);  
	        groupBySelect.setValue("col2");
	        

	        layout.addMember(new Label("<b><nobr>Activity Wise Report</<nobr></b>"));
	        layout.addMember(form);  
	        IButton searchButton = new IButton("Chart");  
	        searchButton.setAutoFit(true);  
	        searchButton.setAlign(Alignment.CENTER);
	        layout.addMember(searchButton);  
	        searchButton.addClickHandler(new ClickHandler() {  
	            @Override  
	            public void onClick(ClickEvent event) {  
	               String fromdt = Util.getDate(reportFromDate.getDisplayValue())+" 00:00:00";
	               String todt = Util.getDate(reportToDate.getDisplayValue())+" 23:59:59";
	                int reportOn = REPORT_ON_COUNT;
	                if(reportType.getValue() != null)
	                if("Points".equals(reportType.getValue().toString())){
	                	reportOn = REPORT_ON_POINTS;
	                }
	                //TODO replace hard coded below parameter with actual
	                generateReport(fromdt, todt, 
	                		activityCombo.getValue()==null ? null : activityCombo.getValue().toString(), 
	                		userTypeCombo.getValue()==null ? null : userTypeCombo.getValue().toString(),
	                		groupBySelect.getValue()==null ? null : groupBySelect.getValue().toString(), reportOn);
//	                generateReport("6/1/11 6:30 AM","05/22/2011 10:01 AM");
	            }  
	        });  
	        
//	        IButton showTableButton = new IButton("Table");  
//	        showTableButton.setAutoFit(true);  
//	        showTableButton.setAlign(Alignment.CENTER);
//	        layout.addMember(showTableButton);  
//	        showTableButton.addClickHandler(new ClickHandler() {  
//	            @Override  
//	            public void onClick(ClickEvent event) {  
//	               String fromdt = Util.getDate(reportFromDate.getDisplayValue())+" 00:00:00";
//	               String todt = Util.getDate(reportToDate.getDisplayValue())+" 23:59:59";
//	                int reportOn = REPORT_ON_COUNT;
//	                if(reportType.getValue() != null)
//	                if("Points".equals(reportType.getValue().toString())){
//	                	reportOn = REPORT_ON_POINTS;
//	                }
//	                //TODO replace hard coded below parameter with actual
////	                generateReport(fromdt, todt, 
////	                		activityCombo.getValue()==null ? null : activityCombo.getValue().toString(), 
////	                		userTypeCombo.getValue()==null ? null : userTypeCombo.getValue().toString(),
////	                		groupBySelect.getValue()==null ? null : groupBySelect.getValue().toString(), reportOn);
////	                generateReport("6/1/11 6:30 AM","05/22/2011 10:01 AM");
//	                displayInTable();
//	            }  
//	        });  
	        
//	        mainPanel.setWidth("600px");
//	        mainPanel.setHeight("600px");
	        layout.addMember(mainPanel);
	        
//	        form.setItems(reportType, createdRangeItem, activityCombo, userTypeCombo, groupBySelect);
//	        form.setItems(reportType);
//	        form.setItems( createdRangeItem);
//	        form.setItems(activityCombo, userTypeCombo, groupBySelect);
//	        form.draw();
	        
	        form.setFields(reportType, reportFromDate, reportToDate, activityCombo, userTypeCombo, groupBySelect);
	        
	        layout.redraw();
//		RootPanel.get("reportCriteriaContainer").add(layout);
	}
	private void generateReport(String fromDate, String toDate, String activity, String userType, String groupBy, int reportOn) {
		// fromDate = "6%2F6%2F11+6%3A30+AM";
		// toDate = "6%2F2%2F11+6%3A30+AM";
		fromDate = URL.encode(fromDate);
		toDate = URL.encode(toDate);
		System.out.println("fromDate : " + fromDate);
		System.out.println("toDate : " + toDate);
		/*
		 select+col2%2C+SUM(col5)+from+954346+where+col3+%3E%3D+'9%2F1%2F2011'+and+col3+%3C%3D+'9%2F8%2F2011'&qrs=+and+col2+%3E%3D+&qre=+and+col2+%3C%3D+&qe=+group+by++col2
select+col2%2C+SUM(col5)+from+954346+where+col3+%3E%3D+'9%2F1%2F2011'+and+col3+%3C%3D+'9%2F8%2F2011'&qrs=+and+col2+%3E%3D+&qre=+and+col2+%3C%3D+&qe=+group+by++col2
select+col2%2C+SUM(col5)+from+954346+where+col3+%3E%3D+'9%2F1%2F2011'+and+col3+%3C%3D+'9%2F8%2F2011'+and+col0+%3D+'like'&qrs=+and+col2+%3E%3D+&qre=+and+col2+%3C%3D+&qe=+group+by++col0%2Ccol2
select+col2%2C+SUM(col5)+from+954346+where+col3+%3E%3D+'9%2F1%2F2011'+and+col3+%3C%3D+'9%2F8%2F2011'+and+col0+%3D+'onTime'&qrs=+and+col2+%3E%3D+&qre=+and+col2+%3C%3D+&qe=+group+by++col0%2Ccol2
select+col2%2C+SUM(col5)+from+954346+where+col3+%3E%3D+'9%2F1%2F2011'+and+col3+%3C%3D+'9%2F8%2F2011'+and+col0+%3D+'clean'&qrs=+and+col2+%3E%3D+&qre=+and+col2+%3C%3D+&qe=+group+by++col0%2Ccol2

select+col4%2C+count()+from+954346+where+col3+%3E%3D+'9%2F1%2F2011'+and+col3+%3C%3D+'9%2F8%2F2011'&qrs=+and+col4+%3E%3D+&qre=+and+col4+%3C%3D+&qe=+group+by++col4

select+col1%2C+count()+from+954346+where+col3+%3E%3D+'9%2F1%2F2011'+and+col3+%3C%3D+'9%2F8%2F2011'+and+col4+%3D+'STF'&qrs=+and+col1+%3E%3D+&qre=+and+col1+%3C%3D+&qe=+group+by++col1
select+col1%2C+count()+from+954346+where+col3+%3E%3D+'9%2F1%2F2011'+and+col3+%3C%3D+'9%2F8%2F2011'+and+col4+%3D+'MGR'&qrs=+and+col1+%3E%3D+&qre=+and+col1+%3C%3D+&qe=+group+by++col1
select+col1%2C+count()+from+954346+where+col3+%3E%3D+'9%2F1%2F2011'+and+col3+%3C%3D+'9%2F8%2F2011'+and+col4+%3D+'VND'&qrs=+and+col1+%3E%3D+&qre=+and+col1+%3C%3D+&qe=+group+by++col1

		 * */
		String query ="select+";
		if(groupBy != null ){
			query += groupBy.replaceAll(",", "%2C")+"%2C";
		}
		if(reportOn == REPORT_ON_POINTS){
			query += "+SUM(col5)+as+Points";
		}else{
			query += "+count()+as+'Activity Count'";
		}
		query += "+from+954346";
		boolean appendAND = false;
		if(fromDate != null || toDate != null 
				|| (activity != null && !"All".equals(activity))
				|| (userType != null && !"All".equals(userType))){
			
			query += "+where";
			if(activity != null && !"All".equals(activity)){
				if(appendAND)
					query += "+and";
				query += "+col0+%3D+";
				query += "'"+activity+"'";
				appendAND = true;
			}
			if(toDate != null){
				if(appendAND)
					query += "+and";
				query += "+col3+%3C%3D+";
				query += "'"+toDate.replaceAll("/", "%2F")+"'";
				appendAND = true;
			}
			if(fromDate != null){
				if(appendAND)
					query += "+and";
				query += "+col3+%3E%3D+";
				query += "'"+fromDate.replaceAll("/", "%2F")+"'";
				appendAND = true;
			}
			
			if(userType != null && !"All".equals(userType)){
				if(appendAND)
					query += "+and";
				query += "+col4+%3D+";
				query += "'"+userType+"'";
				appendAND = true;
			}
			if(groupBy != null ){
				query += "&qrs=+and+col3+%3E%3D+&qre=+and+col3+%3C%3D+&qe=+group+by+";
				query += groupBy.replaceAll(",", "%2C");
				appendAND = true;
			}
		}
		
		System.out.println("query : "+query);
		// HTML chart = new
		// HTML("<iframe width=\"500px\" height=\"300px\" scrolling=\"no\" frameborder=\"no\" src=\"http://www.google.com/fusiontables/embedviz?gco_chartArea=%7B%22top%22%3A%2230%22%7D&containerId=gviz_canvas&q=select+col1%2C+AVERAGE(col2)+from+930600+where+col3+%3C%3D+'6%2F6%2F11+6%3A30+AM'+and+col3+%3E%3D+'6%2F2%2F11+6%3A30+AM'&qrs=+and+col1+%3E%3D+&qre=+and+col1+%3C%3D+&qe=+group+by++col1+limit+2&viz=GVIZ&t=BAR&width=500&height=300\"></iframe>");
		HTML chart = new HTML(
				"<iframe width=\"500px\" height=\"300px\" scrolling=\"no\" frameborder=\"no\" src=\"http://www.google.com/fusiontables/embedviz?gco_chartArea=%7B%22top%22%3A%2230%22%7D&containerId=gviz_canvas&isXyPlot=true&q=" +
						query + "&viz=GVIZ&t=BAR&width=500&height=300\"></iframe>");

		if (mainPanel.getWidgetCount() > 0)
			mainPanel.remove(0);
		mainPanel.add(chart);
//		 layout.redraw();
	}
	private void displayInTable(){
		StringBuilder htmlStr = new StringBuilder();
		htmlStr.append("<div id=\"visualization\"></div> ");
		htmlStr.append("<table><tr><td>");
		
		htmlStr.append("google.load('visualization', '1', {'packages':['table']});");

		htmlStr.append("function changeData(scorer) {");
		htmlStr.append("var whereClause = \"\";");
		htmlStr.append("if(scorer) {");
		htmlStr.append("whereClause =  \" WHERE 'Scoring Team' = '\" + scorer + \"'\";");
		htmlStr.append("}");
		htmlStr.append("var queryText = encodeURIComponent(\"SELECT 'Scoring Team', 'Receiving Team', 'Minute of goal' FROM 197026\" + whereClause);");
		htmlStr.append("var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq='  + queryText);");
		  
		htmlStr.append("query.send(getData);");
		htmlStr.append("}");

		htmlStr.append("function getData(response) {");
		htmlStr.append("var table = new google.visualization.Table(document.getElementById('visualization'));");
		htmlStr.append("table.draw(response.getDataTable(), {showRowNumber: true});");
		htmlStr.append("</td></tr></table>");
		HTML table = new HTML(htmlStr.toString());
		if (mainPanel.getWidgetCount() > 0)
			mainPanel.remove(0);
		mainPanel.add(table);
	}

}
